package net.stogi.unicore.beyond.io.input.integerfield;

import java.util.Map;

import net.stogi.common.api.exception.Messages;
import net.stogi.unicore.beyond.api.model.PropertyValue;
import net.stogi.unicore.beyond.io.input.core.InputValidator;
import net.stogi.unicore.beyond.io.input.core.PropertyUtils;

public class IntegerInputValidator implements InputValidator {

	@Override
	public boolean validate(String inputName, String inputValue, Map<String, PropertyValue> properties, Messages messages) {
		boolean valid = true;

		// Not empty.
		{
			boolean empty = PropertyUtils.asBoolean(properties.get("empty"));
			if (!empty && inputValue == null) {
				messages.error(inputName, "Field can not be empty");
				return false;
			}
		}
		if (inputValue != null) {
			Integer value = Integer.parseInt(inputValue);
			// Maximal value.
			{
				Integer max = PropertyUtils.asInteger(properties.get("max"));
				if (max != null && value > max) {
					messages.error(inputName, String.format("Field value can not be more than %1$d", max));
					valid = false;
				}
			}
			// Minimal value.
			{
				Integer min = PropertyUtils.asInteger(properties.get("min"));
				if (min != null && value < min) {
					messages.error(inputName, String.format("Field value can not be less than %1$d", min));
					valid = false;
				}
			}
			// Match regex.
//		{
//			String regex = PropertyUtils.asString(properties.get("regex"));
//			if (regex != null && !inputValue.matches(regex)) {
//				messages.error(inputName, String.format("Field value has to match regular expression: '%1$s'", regex));
//				valid = false;
//			}
//		}
		}

		return valid;
	}
}
